<?php
/**
 * Admin module manage Controller
 *
 * module manage
 *
 *
 * @version $Id: ManagerController.php 98 2010-05-09 09:12:40Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Zend_Controller_Action
 * @package admin
 * @subpackage Controller
 */
class Admin_ManagerController extends Zend_Controller_Action
{

    function indexAction()
    {
        $this->_redirect('admin/manager/list');
    }

    function listAction()
    {

        $id = $this->_getParam('id');
        $this->view->hidden_id = $id;
        //$resource = new Default_Model_DbTable_AclResourcesView();
        $resource = new Default_Model_AclResourcesView();
        //列出模組
        $this->view->resources = $resource->getResource($id);
        //列出子模組數
        $this->view->resChild = $resource->getChildCount($id);
        // 上方導覽
        $this->view->moduleNavMenu = $resource->getNavMenu($id);

        // $module = new Default_Model_Module();
        // 授權類別
        //  $this->view->roleKind = $module->getRoleKind();
        //        echo '<pre>';
        //        print_r($module->getModuleMenu());
        // 分類選單
        // $this->view->moduleMenu = $module->getModuleMenu('',$this->view->translate('topPage'));

    }

    /**
     * 模組修改
     * @return unknown_type
     */
    function editAction()
    {
        $this->getHelper('layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNorender();
        $reload = $this->_request->getParam('id');
        $form = new Admin_Form_Manager();
        if ($this->_request->isPost()){
            $request = $this->getRequest();
            if($form->isValid($request->getParams())){
                $resourceId = $this->_request->getParam('resource_id');
                $accessId = $this->_request->getParam('id');

                // 設定模組名稱
                $resources =  new Default_Model_Resources();
                $resources->assignIdentifier($resourceId);
                $resources->title = $this->_request->getParam('title');
                $resources->save();

                $parentId = $this->_request->getParam('parent_id');
                if ($parentId=='') $parentId = NULL;
                //設定所屬分類
                $aclResource = new Default_Model_AclResources();
                $aclResource->assignIdentifier($accessId);
                if ( $aclResource->parent_id <> $parentId and $resourceId<>$parentId ) { // parent_id有改變 且 parent_id 和 id 不可重複
                    $aclResource->parent_id = $parentId;
                    $aclResource->save();
                    $reload = 'reload';
                }
                // TODO 設定權限
                // privilege of action
                $setid  = $this->_request->getParam('item_id');

                if ($setid) {
                    $allow = $this->_request->getParam('allow',1);
                    $controller = null;
                    $aclController = $this->_request->getParam('acl_controller');
                    $controllerCount = $this->_request->getParam('controller_count');
                    if (count($aclController) < $controllerCount )
                    $controller = implode(":",$this->_request->getParam('acl_controller'));
                    // 檢查是否已有重覆
                    $q= Doctrine_Query::create()
                    ->select('id')
                    ->from('Default_Model_AclAccess');
                    if ($controller === null)
                    $q->where('controller IS NULL');
                    else
                    $q->where('controller=?', $controller);

                    $q->andWhere('resource_id=?', $accessId)
                    ->andWhere('role_id=?', $setid)
                    ->andWhere('allow=?', $allow);
                    $res = $q->fetchOne();
                    if (!$res) {
                        $aclAccess  = new Default_Model_AclAccess();
                        $aclAccess->controller = $controller;
                        $aclAccess->resource_id = $accessId;
                        $aclAccess->role_id = $setid;
                        $aclAccess->allow = $allow;
                        $aclAccess->save();
                    }
                    else
                    $reload = 0;
                }
                $this->_helper->ResetAclResources();
            }
            //$this->_redirect('admin/manager/index/id/'.$parent_id);
        }
        echo $reload;
        //$this->_redirect('/');

    }



    /**
     * 刪除權限
     * @return JSON TYPE
     */

    function delaccessAction()
    {
        $id = $this->_request->getParam('id',0);
        if ($id > 0 ) {
            $aclAccessTable = Doctrine::getTable('Default_Model_AclAccess');
            $aclAccess = $aclAccessTable->find($id);
            if ($aclAccess !== false)
            $aclAccess->delete();
            // 重設acl
            $this->_helper->resetAclResources();
            $this->_helper->json($id);
        }
    }

    /*
     * 新增模組 表單 AJAX FORM
     *
     */
    function formsetAction()
    {
        $this->getHelper('layout')->disableLayout();
        $id = $this->_request->getParam('id','');

        if ($id <>'' ) {
            // 模組設定
            $aclResourceView = Doctrine::getTable('Default_Model_AclResourcesView');
            $response = $aclResourceView->findOneBy('id',$id)->toArray();
            $form = new Admin_Form_Manager();
            //            $response['module'] = $this->_getXml($response['resource_id']);
            //            print_r($response['module']);
            $form->setDefaults($response);
            $this->view->form = $form;
            //	$this->_helper->json($response);
            $this->view->parentId = $response['resource_id'];
            $acl = new Default_Model_AclResourcesAccessView();
            $this->view->id= $id;
            $data = $acl->getAccessTree($id);
            $this->view->data= $data;
            $ss = $acl->getTable()->findOneById($id)->toArray();
            if (count($data)){
                //                // 顯示授權項目名稱
                if ($ss['kind'] == 'module') {
                    $translate = Zend_Registry::get('Zend_Translate');
                    $tr_name = APPLICATION_PATH.'/modules/'.$ss['resource_id'].'/languages/'.$translate->getLocale().'/'.
                    $ss['resource_id'].'.php';
                    if (is_file($tr_name)){
                        $translate->addTranslation($tr_name);
                    }
                    $xmlFile = APPLICATION_PATH.'/modules/'.$ss['resource_id'].'/module.xml';
                    if (is_file($xmlFile)) {
                        $xml = simplexml_load_file($xmlFile);
                        $arr = array();
                        foreach($xml->xpath("//item") as $val) {
                            $arr[(string)$val->url] = $val;
                        }
                        $this->view->controllerData = $arr;
                    }
                }
                // 參數調整
                $this->_init_paramForm($ss['resource_id']);
            }
        }
    }


    /**
     * 儲存參數
     * @return unknown_type
     */
    public function setParamAction()
    {
        $request = $this->getRequest();
        $resourse_id = $request->getParam('PARAM_RESOURCE_ID');
        if ($request->isPost()) {
            $form = $this->_init_paramForm($resourse_id);
            if ($form->isValid($request->getParams())){
                foreach($form->getValues() as $id=>$val) {
                    if ($id=='PARAM_RESOURCE_ID' or $id=='PARAM_SAVE')
                    continue;
                    unset($arr);
                    $arr['resource_id'] = $resourse_id;
                    $arr['param'] = $id;
                    $arr['value'] = $val;
                    $q = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Default_Model_ModulesParam')
                    ->where('resource_id=?',$resourse_id)
                    ->where('param=?',$id);
                    $res = $q->fetchOne();
                    if ($res) {
                        $q = Doctrine_Query::create()
                        ->update('Default_Model_ModulesParam')
                        ->set('value', '?', $val)
                        ->where('resource_id=?', $resourse_id)
                        ->andWhere('param=?', $id);
                        $q->execute();
                    }
                    else{
                        $moduleParam = new Default_Model_ModulesParam();
                        $moduleParam->fromArray($arr);
                        $moduleParam->save();
                    }
                }
                $this->_helper->ResetAclResources();
                $this->_helper->json(1);
            }
            else
            $this->_helper->json(array('error'=>$form->getMessages()));
        }
        $this->_helper->json(array('error'=>'error'));
    }


    /**
     * 參數調整
     * @param unknown_type $resource_id
     * @return unknown_type
     */
    function _init_paramForm($resource_id)
    {
        $translate = Zend_Registry::get('Zend_Translate');
        $xml_file = APPLICATION_PATH.'/modules/'.$resource_id.'/module.xml';
        if (is_file($xml_file)) {
            $xml = new Zend_Config_Xml($xml_file);
            $this->view->xml = $xml;
            $form = new Sfs_Form($xml->param);
            $form->setAttrib('id','paramForm');
            $form->addElement('submit','PARAM_SAVE',array(
                        'label'=>'save'
                        ))
                        ->addElement('hidden','PARAM_RESOURCE_ID',array(
                       'required'=>true,
                        ));
                        $form->getElement('PARAM_RESOURCE_ID')->setValue($resource_id);
                        // 預設值
                        $module_default = APPLICATION_PATH.'/modules/'.$resource_id.'/languages/'.$translate->getLocale().'/'.
				'module-cfg-default.php';
                        $module_default_arr = array();
                        if (is_file($module_default)) {
                            $module_default_arr = include(realpath($module_default));
                            $form->setDefaults($module_default_arr);
                        }
                        // 已在資料回復
                        $res = Doctrine_Query::create()
                        ->from('Default_Model_ModulesParam')
                        ->where('resource_id=?', $resource_id)
                        ->fetchArray();
                        if ($res) {
                            $new_param = array();
                            foreach($res as $val) {
                                $form->setDefault($val['param'],$val['value']);
                                $new_param[]= $val['param'];
                            }
                            $module_default_arr_index = array_keys($xml->param->elements->toarray());

                            $this->view->new_param = Zend_Json::encode(array_diff($module_default_arr_index,$new_param));

                        }

                        $this->view->paramform = $form;


                        $tr_name = APPLICATION_PATH.'/modules/'.$resource_id.'/languages/'.$translate->getLocale().'/'.
				'module-cfg.php';
                        //                        echo $tr_name; exit;
                        if (is_file($tr_name)){
                            $translate->addTranslation($tr_name);
                        }
                        return $form;
        }
        return false;
    }


    /**
     * 授權項目
     * @return unknown_type
     */
    function getitemsAction()
    {
        $this->getHelper('layout')->disableLayout();
        //$this->getHelper('ViewRenderer')->setNorender();
        $module = $this->_request->getParam('id',0);

        $translate = Zend_Registry::get('Zend_Translate');
        $tr_name = APPLICATION_PATH.'/modules/'.$module.'/languages/'.$translate->getLocale().'/'.
        $module.'.php';
        if (is_file($tr_name)){
            $translate->addTranslation($tr_name);
        }
        $this->view->data = simplexml_load_file(APPLICATION_PATH.'/modules/'.$module.'/module.xml');

        //$this->_helper->json($str);
    }

    /**
     * 取模組權限列表
     * @return unknown_type
     */
    function getAuthorizedAction()
    {
        $this->getHelper('layout')->disableLayout();
        $id = (int)$this->getRequest()->getParam('id',0);
        $aclResourcesAccessView = new Default_Model_AclResourcesAccessView();
        $arr = $aclResourcesAccessView->getAclUsers($id);

        $this->view->data = $arr;
        if (count($arr) > 0) {
            $aclResources = new Default_Model_AclResources();
            $row = $aclResources->getTable()->findBy('id',$id)->getFirst();
            $resourceId = $row->resource_id;
            $xmlFile = APPLICATION_PATH.'/modules/'.$resourceId.'/module.xml';
            if (is_file($xmlFile)) {
                $translate = Zend_Registry::get('Zend_Translate');
                $trName = APPLICATION_PATH.'/modules/'.$resourceId.'/languages/'.$translate->getLocale().'/'.
                $resourceId.'.php';
                if (is_file($trName)){
                    $translate->addTranslation($trName);
                }

                $xml = simplexml_load_file($xmlFile);
                $arr = array();
                $xmlMenu = $xml->xpath("//menu/item");
                foreach($xmlMenu as $aa){
                    $arr[(string)$aa->url] = (string)$aa->name;
                }
                $this->view->cMenu= $arr;
            }
        }
    }

    /**
     *
     * 權限授權
     * @return unknown_type
     */
    function getaclaccessAction()
    {

        // TODO 新增查詢所有擁有權限人員列表
        $this->getHelper('layout')->disableLayout();
        $id = $this->_request->getParam('id',0);

        $acl = new Default_Model_AclResourcesAccessView();
        //$data = $acl->fetchAll("id=$id AND role_id IS NOT NULL");

        $this->view->id= $id;

        $data = $acl->getAccessTree($id);
        $this->view->data= $data;
        if (count($data)){
            // 顯示授權項目名稱
            $aclResources = new Default_Model_AclResources();
            $row = $aclResources->getTable()->findBy('id',$id)->getFirst();
            $resourceId = $row->resource_id;
            $xmlFile = APPLICATION_PATH.'/modules/'.$resourceId.'/module.xml';
            if (is_file($xmlFile)) {
                $translate = Zend_Registry::get('Zend_Translate');
                $trName = APPLICATION_PATH.'/modules/'.$resourceId.'/languages/'.$translate->getLocale().'/'.
                $resourceId.'.php';
                if (is_file($trName)){
                    $translate->addTranslation($trName);
                }

                $xml = simplexml_load_file($xmlFile);
                $arr = array();
                $xmlMenu = $xml->xpath("//menu/item");
                foreach($xmlMenu as $aa){
                    $arr[(string)$aa->url] = (string)$aa->name;
                }
                $this->view->cMenu= $arr;
            }
        }
    }

    /**
     * 取得不同授權群組
     * @return unknown_type
     */
    function getitemAction()
    {
        $kind = $this->_request->getParam('kind');
        $module = new Default_Model_Module();
        $data = $module->getPerrItem($kind);
        $dojo_data = new Zend_Dojo_Data('sn',$data);
        $dojo_data->setLabel('item');
        $this->_helper->json($dojo_data);
    }


    /**
     * 儲存排序及啟動訊息
     *
     */
    function modulesaveAction()
    {
        if ($this->_request->isPost()){
            $sdata = $this->_getParam('sort');
            $pdata = $this->_getParam('published');

            $resource = new Default_Model_Resources();
            foreach($sdata  as $id=>$val) {
                $resource->assignIdentifier($id);
                if ($resource->published < 9 ) {
                    $p = @$pdata[$id];
                    if ($p=='') $p = 0;
                    $resource->published = $p;
                }
                $resource->sort = $val;
                $resource->save();
            }
        }
        // 重設acl
        $cache = Zend_Registry::get('cache');
        $cache->remove('acl_cache');
        //        $this->view->infoMenssage='設定完成';
        $this->_redirect('admin/manager/list/id/'.$this->_getParam('id'));
    }


    /**
     * 取得模組設定
     *
     * @param string $module
     * @return Object | boolean
     */

    function _getXml($module)
    {
        $module_xml = APPLICATION_PATH.'/modules/'.$module.'/module.xml';
        if (is_file($module_xml)) {
            return  file_get_contents($module_xml);
        }
        else
        return false;
    }

    /**
     * 取得模組參數表
     * @return unknown_type
     */
    function getparamsAction()
    {
        $this->getHelper('layout')->disableLayout();
        $id = $this->_request->getParam('id',0);
        $acl_resource = new acl_resources();
        if ($id){
            $row = $acl_resource->fetchRow("id=$id");
            $module = $row->resource_id;
            $modues = new Modules();
            $row = $modues->fetchRow("id='$module'");
            // 設定值
            if ($row) {
                $this->view->param_data = unserialize($row->params);
            }

            $this->view->id = $module;
            $xml_file = Bootstrap::getPath('modules').'/'.$module.'/module.xml';
            if (is_file($xml_file)){
                $module_xml = simplexml_load_file($xml_file);
                $this->view->params = $module_xml->xpath("//param");

            }

        }
    }

    /**
     * 設定模組參數
     * @return unknown_type
     */
    function setparamsAction()
    {
        $module = $this->_request->getParam('resource_id',0);

        $xml_file = Bootstrap::getPath('modules').'/'.$module.'/module.xml';
        if (is_file($xml_file)){
            $params_arr = array();
            $module_xml = simplexml_load_file($xml_file);
            $params = $module_xml->xpath("//param");
            foreach ($params as $val) {
                $data = $val->attributes();
                $var_name = (string)$data['name'];
                $params_arr[$var_name] = $this->_request->getParam($var_name,'');
            }
            $module = new Modules();
            $row = $module->fetchRow("id='$id'");
            if (!$row) {
                $row = $module->createRow();
                $row->id = $id;
            }
            $row->params = serialize($params_arr);
            $row->save();
        }
        $this->_helper->json('1');
    }
}
